#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

int fd;    unsigned
char buf[16];


int main(int argc, char *argv[])
{
    int ret;  
    int recv_cnt;
    int offset;



    if (argc < 2)
    {
        printf("%d\r\n", argc);

        printf("plase input paraments\r\n");
        return -1;
    }

    // 以非阻塞方式打开设备
    fd = open(argv[1], O_RDWR , 0666);
    if (fd < 0)
    {
        
        printf(" open %s is error: %s\r\n", argv[1], strerror(errno));
        return -1;
    }
    printf("open %s is ok\r\n", argv[1]);

    if (argc > 2)
    { 
        if (! strcmp(argv[2], "read"))
        {
            offset = lseek(fd, 0, SEEK_CUR);
            printf("read before offset : %d \n", offset);
            recv_cnt = read(fd, buf, sizeof(buf));
            if (recv_cnt < 0)
            {
                printf(" read %d is error: %s\r\n", fd, strerror(errno));
                return -1;
            }
            printf("read[%d] : %s\n", sizeof(buf), buf);
            offset = lseek(fd, 0, SEEK_CUR);
            printf("read after offset : %d \n", offset);
            // sleep(1);
        } else if (! strcmp(argv[2], "write"))
        {
            if (argc > 3)
            {
                offset = lseek(fd, 0, SEEK_CUR);
                printf("write before offset : %d \n", offset);
                write(fd, argv[3], strlen(argv[3]));
                offset = lseek(fd, 0, SEEK_CUR);
                printf("write after offset : %d \n", offset);
            }
            else {
                // 设定偏移
                offset = lseek(fd, 0, SEEK_SET);
                printf("offset : %d \n", offset);
                write(fd, "nihao!!", sizeof("nihao!!"));
            }
            
        }
    }

    close(fd);

    return 0;
}
